<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>University Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f7f7f7;
        }

        .chat-container {
            width: 100%;
            max-width: 400px;
            margin: auto;
            border: 1px solid #dedede;
            background-color: #fff;
            border-radius: 5px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .chat-header {
            background-color: #4e8cff;
            color: #fff;
            padding: 15px;
            text-align: center;
            position: relative;
            line-height: 1.8em;
        }

        .chat-header img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 10px;
            transform: translateY(-50%);
        }

        .chat-header h2 {
            margin: 0;
            padding: 0;
            font-size: 18px;
            line-height: 50px;
        }

        .chat-box {
            padding: 10px;
            height: 500px;
            overflow-y: auto;
        }

        .chat-box .message {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .chat-box .message .avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
        }

        .chat-box .message .text {
            max-width: 70%;
            margin-left: 10px;
            padding: 10px;
            border-radius: 5px;
            background-color: #f1f1f1;
        }

        .chat-box .message.user .text {
            background-color: #4e8cff;
            color: #fff;
            margin-left: auto;
            margin-right: 10px;
        }

        .chat-input {
            display: flex;
            padding: 10px;
            border-top: 1px solid #dedede;
        }

        .chat-input input {
            flex: 1;
            padding: 10px;
            margin-right: 6px;
            border: 1px solid #dedede;
            border-radius: 3px;
            outline: none;
        }

        .chat-input button {
            padding: 10px 15px;
            background-color: #4e8cff;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            outline: none;
        }

        .chat-input button:hover {
            background-color: #1a70d1;
        }

        .toggle {
            position: relative;
            display: block;
            width: 55px;
            height: 28px;
            margin-left: -7px;
            padding: 3px;
            margin: auto;
            border-radius: 50px;
            cursor: pointer;
        }

        .toggle-input {
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
        }

        .toggle-label {
            position: relative;
            display: block;
            height: inherit;
            font-size: 12px;
            background: rgb(103, 96, 96);
            border-radius: inherit;
            box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12), inset 0 0 3px rgba(0, 0, 0, 0.15);
        }

        .toggle-label:before,
        .toggle-label:after {
            position: absolute;
            top: 50%;
            color: black;
            margin-top: -.5em;
            line-height: 1;
        }

        .toggle-label:before {
            content: attr(data-off);
            right: 11px;
            color: #fff;
            text-shadow: 0 1px rgba(255, 255, 255, 0.5);
        }

        .toggle-label:after {
            content: attr(data-on);
            left: 11px;
            color: #fff;
            text-shadow: 0 1px rgba(0, 0, 0, 0.2);
            opacity: 0;
        }

        .toggle-input:checked ~ .toggle-label {
            background: green;
        }

        .toggle-input:checked ~ .toggle-label:before {
            opacity: 0;
        }

        .toggle-input:checked ~ .toggle-label:after {
            opacity: 1;
        }

        .toggle-handle {
            position: absolute;
            top: 4px;
            left: 4px;
            width: 25px;
            height: 26px;
            background: linear-gradient(to bottom, #FFFFFF 40%, #f0f0f0);
            border-radius: 50%;
        }

        .toggle-handle:before {
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -6px 0 0 -6px;
            width: 16px;
            height: 16px;
        }

        .toggle-input:checked ~ .toggle-handle {
            left: 32px;
            box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
        }

        /* Transition*/
        .toggle-label,
        .toggle-handle {
            transition: All 0.3s ease;
            -webkit-transition: All 0.3s ease;
            -moz-transition: All 0.3s ease;
            -o-transition: All 0.3s ease;
        }

        .main-box {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
        }

        .custom-submit-btn {
            display: inline-block;
            padding: 10px 20px;
            background-color: #4e8cff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            border: none;
            text-align: center;
            text-decoration: none;
            font-size: 16px;
        }

        .custom-upload-btn {
            text-align: center;
            display: inline-block;
            padding: 10px 20px;
            background-color: #4e8cff;
            color: white;
            margin-left: 5px;
            border-radius: 5px;
            cursor: pointer;
            position: relative;
            width: 330px;
            overflow: hidden;
        }

        .hidden-file-input {
            position: absolute;
            top: 0;
            right: 0;
            opacity: 0;
            cursor: pointer;
        }

        form {
            display: flex;
        }

        .button {
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
            width: 40%;
        }

        .button:hover {
            background-color: #4e8cff;
        }

        .button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .button-box {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }
    </style>
</head>

<body>

<div class="main-box">
    <div class="chat-container">
        <div class="chat-header">
            <h3>Mongolian National University of Education Tool Text To Speech</h3>
        </div>
        <div id="chat-box" class="chat-box">
            <!-- Messages will be displayed here -->
        </div>
        <div class="chat-input">

            <input type="text" id="message-input" placeholder="Type your message..." required>
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <div class="chat-container">
        <div class="chat-header">
            <h3>Mongolian National University of Education Tool Speech To Text</h3>
        </div>
        <div id="chat-box2" class="chat-box">
            <!-- Messages will be displayed here -->
        </div>
        <div class="chat-input">
            <div class="button-box">
                <button id="start" class="button">Start Recording</button>
                <button id="stop" class="button" disabled>Stop Recording</button>
            </div>
        </div>
    </div>
</div>

<!-- tts -->
<script>

    document.getElementById("message-input").addEventListener("keypress", function (event) {
        if (event.keyCode === 13) {
            sendMessage();
            event.preventDefault();
        }
    });

    function sendMessage() {
        var input = document.getElementById("message-input");
        var chatBox = document.getElementById("chat-box");
        if (input.value.trim() !== '') {

            var userDiv = document.createElement("div");
            userDiv.classList.add("message", "user");
            userDiv.innerHTML = `
                <div class="text">${input.value}</div>
            `;
            chatBox.appendChild(userDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
            get_info(input.value)
            input.value = '';
        } else {
            alert("请输入内容")
        }

    }


    function get_info(text) {


        fetch('/tts?text=' + text)
            .then(response => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Network response was not ok.');
            })
            .then(data => {
                // 处理获取到的数据
                console.log(data);
                cre_audio_response(data['filePath'])
            })
            .catch(error => {
                // 处理错误
                console.error('Error:', error);
            });
    }

    function cre_audio_response(res) {
        setTimeout(function () {
            var chatBox = document.getElementById("chat-box");
            var botDiv = document.createElement("div");
            botDiv.classList.add("message", "bot");
            botDiv.innerHTML = `
                <div class="text">
                    <audio controls>
                        <source src="/audio/${res}" type="audio/mpeg">
                        Your browser does not support the audio element.
                    </audio>
                </div>

            `;
            chatBox.appendChild(botDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }, 1000)
    }
</script>

<!-- stt -->
<script>
    var mediaRecorder;
    var chunks = [];
    var audioBlob;

    document.getElementById('start').addEventListener('click', startRecording);
    document.getElementById('stop').addEventListener('click', stopRecording);

    function startRecording() {
        navigator.mediaDevices.getUserMedia({audio: true})
            .then(function (stream) {
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.start();

                document.getElementById('start').disabled = true;
                document.getElementById('stop').disabled = false;

                mediaRecorder.addEventListener("dataavailable", function (event) {
                    chunks.push(event.data);
                });
            });
    }

    function stopRecording() {
        mediaRecorder.stop();

        document.getElementById('start').disabled = false;
        document.getElementById('stop').disabled = true;

        mediaRecorder.addEventListener("stop", function () {
            audioBlob = new Blob(chunks, {type: "audio/webm"});
            // 将音频文件发送到服务器
            sendAudioToServer(audioBlob);
        });
    }

    function cre_message_response(message, path) {
        setTimeout(function () {


            var chatBox = document.getElementById("chat-box2");
            var userDiv = document.createElement("div");
            userDiv.classList.add("message", "user");
            userDiv.innerHTML = `
                <div class="text" style="background-color: white">
                    <audio controls>
                        <source src="/useraudio/${path}" type="audio/mpeg">
                        Your browser does not support the audio element.
                    </audio>
                </div>
            `;
            chatBox.appendChild(userDiv);
            chatBox.scrollTop = chatBox.scrollHeight;


            var chatBox = document.getElementById("chat-box2");
            var botDiv = document.createElement("div");
            botDiv.classList.add("message", "bot");
            botDiv.innerHTML = `
                <div class="text">
                    ${message}
                </div>

            `;
            chatBox.appendChild(botDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }, 1)
        chunks=[]
    }


    function sendAudioToServer(blob) {
        var formData = new FormData();
        formData.append('audio', blob);

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Network response was not ok.');
            })
            .then(data => {
                // 处理获取到的数据
                console.log(data);
                cre_message_response(data['result'], data['fileName'])
            })
            .catch(error => console.error(error));
    }
</script>

</body>

</html>